<?php


class LearnService extends Service
{
  /**
   * @param string $className
   * @return LearnService
   */
  public static function instance($className = __CLASS__)
  {
    return parent::instance($className);
  }

  /**
   * 检查学习状态
   * @param int $article_id
   * @param int $user_id
   * @return bool
   */
  public function isLearned($article_id = 0, $user_id = 0)
  {
    if (Yii::app()->user->getState('type') != 1) {
      return false;
    }
    $data = Learn::model()->findByAttributes(array('article_id' => $article_id, 'user_id' => $user_id));
    return empty($data) ? false : true;
  }

  /**
   * 学习
   * @param int $article_id
   * @param int $user_id
   * @return bool
   */
  public function learn($article_id = 0, $user_id = 0)
  {
    //如果学过了
    if ($this->isLearned($article_id, $user_id)) {
      return false;
    }
    $learn = new Learn();
    $learn->article_id = $article_id;
    $learn->user_id = $user_id;
    return $learn->save() ? true : false;
  }

  /**
   * 我的课程列表
   * @param int $user_id
   * @param string $keywords
   * @param int $pageSize
   * @return array
   */
  public function getList($user_id = 0, $keywords = '', $pageSize = 20)
  {
    $criteria = new CDbCriteria();
    $criteria->condition = 'learn.user_id=:user_id';
    $criteria->params = array(':user_id' => $user_id);
    //关键字
    if (!empty($keywords)) {
      $criteria->addSearchCondition('article.title', $keywords);
    }
    //关联
    $criteria->with = array(
        'user',
        'article'
    );
    $criteria->order = 'article.hits desc,article.created_at desc';
    $count = Learn::model()->count($criteria);
    $pages = new CPagination($count);
    $pages->pageSize = $pageSize;
    $pages->applyLimit($criteria);
    $criteria->offset = $pages->currentPage * $pages->pageSize;
    $list = Learn::model()->findAll($criteria);
    return array(
        'list' => $list,
        'pages' => $pages
    );
  }
} 